package com.wlts.wzy.KSUserModule.controller;


import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.ks.GetMyKsOauthRequest;
import com.wlts.wzy.api.request.ks.LoginKsUserRequest;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 快手授权信息 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-02-01
 */
@Api(tags = "快手商铺用户 前端控制器")
@RestController
@RequestMapping("/KSUserModule/ks-store-user")
public class KsStoreUserController {
    @Autowired
    private IKsStoreUserService ksStoreUserService;

    @ApiOperation(value = "快手商铺用户登录")
    @RequestMapping(value = "LoginKsStoreUser", method = RequestMethod.POST)
    public Result<KsStoreUser> LoginKsStoreUser(@RequestBody LoginKsUserRequest request) {

        MyLambdaQueryWrapper<KsStoreUser> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(KsStoreUser::getName, request.getName());

        wrapper.eq(BaseEntity::getDelFlag,"0");

        //      wrapper.eq(KsStoreUser::getPassword, MD5.md5(request.getPassword()));

        KsStoreUser ksStoreUser = ksStoreUserService.getOne(wrapper);

        if (ksStoreUser == null) {
            return Result.buildResult(500,"用户不存在");
        }

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(ksStoreUser.getName() + "|ks", MD5.md5(request.getPassword()));

        //将存有用户名和密码的token存进subject中
        subject.login(token);

        ksStoreUser.setToken(subject.getSession().getId().toString());

        return Result.buildResult(ksStoreUser);
    }

    @ApiOperation(value = "获得我的用户信息")
    @RequestMapping(value = "getMyKsStoreUser", method = RequestMethod.POST)
    public Result<KsStoreUser> getMyKsStoreUser(@RequestBody GetMyKsOauthRequest request) {

        MyLambdaQueryWrapper<KsStoreUser> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(KsStoreUser::getUuid, request.getUserUuid());

        wrapper.eq(BaseEntity::getDelFlag,"0");

        //      wrapper.eq(KsStoreUser::getPassword, MD5.md5(request.getPassword()));

        KsStoreUser ksStoreUser = ksStoreUserService.getOne(wrapper);

        if (ksStoreUser == null) {
            return Result.buildResult(500,"用户不存在");
        }

        return Result.buildResult(ksStoreUser);
    }

}
